package com.xinxing.learning.datasource.aop;

import com.xinxing.learning.datasource.annotation.DataSourceRoute;
import com.xinxing.learning.datasource.config.DynamicDataSource;
import com.xinxing.learning.datasource.context.DynamicContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class DataSourceAspect {

    @Pointcut("@annotation(com.xinxing.learning.datasource.annotation.DataSourceRoute) " +
            "|| @within(com.xinxing.learning.datasource.annotation.DataSourceRoute)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Class targetClass = point.getTarget().getClass();
        Method method = signature.getMethod();

        DataSourceRoute targetDataSource = (DataSourceRoute) targetClass.getAnnotation(DataSourceRoute.class);
        DataSourceRoute methodDataSource = method.getAnnotation(DataSourceRoute.class);
        if (targetDataSource != null || methodDataSource != null) {
            String value;
            if (methodDataSource != null) {
                value = methodDataSource.value();
            } else {
                value = targetDataSource.value();
            }
            //根据dbKey动态设置数据源
            DynamicDataSource.setDataSource(value);
            log.info("set datasource is {}", value);
        }

        try {
            return point.proceed();
        } finally {
            DynamicContextHolder.poll();
            log.info("clean datasource");
        }
    }
}
